package cn.jtfadmin.base.shiro.controller;

import cn.jtfadmin.base.lang.common.domain.dto.NameValueDTO;
import cn.jtfadmin.base.lang.common.domain.dto.ResultDTO;
import cn.jtfadmin.base.lang.common.security.UserDetails;
import cn.jtfadmin.base.lang.config.user.UserHolder;
import org.apache.shiro.mgt.SessionsSecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionManager;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * shiro Controller,权限系统controller
 */
@RestController
public class ShiroController {

    @Autowired()
    private SessionsSecurityManager securityManager;

    @Autowired
    private ShiroFilterChainDefinition shiroFilterChainDefinition;


    /**
     * 获取在线用户总数
     * @return 在线用户总数
     */
    @GetMapping(value = "/baseShiro/getActiveNum")
    public ResultDTO<Integer> getActiveNum(){
        DefaultSessionManager sessionManager = (DefaultSessionManager) securityManager.getSessionManager();
        Collection<Session> activeSessions = sessionManager.getSessionDAO().getActiveSessions();
        return ResultDTO.successData(activeSessions.size());
    }


    /**
     * 获取url过滤器链
     * @param url 过滤的url
      * @return
     */
    @GetMapping(value = "/baseShiro/getUrlFilterChain")
    public ResultDTO<List<NameValueDTO>> getUrlFilterChain(@RequestParam(required = false) String url){
        if(!StringUtils.hasText(url)){
            url = "";
        }
        try {
            url = URLDecoder.decode(url, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            //
        }
        String finalUrl = url;
        Map<String, String> filterChainMap = shiroFilterChainDefinition.getFilterChainMap();
        return ResultDTO.successData(
                filterChainMap.entrySet().stream()
                .filter(entry -> entry.getKey().contains(finalUrl))
                .map(entry -> new NameValueDTO(entry.getKey(), entry.getValue()))

                .collect(Collectors.toList())
        );
    }


    /**
     * 验证用户token
     * @param type 验证是否是此用户类型
     * @return
     */
    @GetMapping(value = "/baseShiro/validateToken")
    public ResultDTO<Boolean> validateToken(@RequestParam(required = false) String type){
        UserDetails userDetails = UserHolder.getUserDetails();
        if(userDetails == null){
            return ResultDTO.successData(false);
        }
        if(StringUtils.hasText(type)){
            Optional<String> optional = userDetails.findUserIdByType(type);
            return ResultDTO.successData(optional.isPresent());
        }
        return ResultDTO.successData(true);
    }
}

